﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Linq;

using Debug = UnityEngine.Debug;

[RequireComponent(typeof(MyCharacterController))]
public class EasyWalkScript : MonoBehaviour
{
    public float speed = 5.0f;
    private VoxelTerrain voxelTerrain;

    private MyCharacterController characterController;

    private List<Point3> WalkList = new List<Point3>();

    void OnEnable()
    {
        voxelTerrain = VoxelTerrain.Instance;
        VoxelTerrain.OnTerrainChangeDelegate += OnTerrainChange;
    }

    void Start()
    {
        Point3 position = Point3.Round(transform.position);
        characterController = GetComponent<MyCharacterController>();
        //transform.position = new Vector3(position.x, voxelTerrain.HeightmapLayer(position.x, position.z) + 1, position.z);

        //WalkList = Pathfinding.FindPath(Point3.RoundToPoint(transform.position), Point3.RoundToPoint(transform.position) + new Point3(1, 0, 0), voxelTerrain);

    }

    void Update()
    {
        RaycastHit hit;
        if (Input.GetMouseButtonDown(1) && Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
        {
            Point3 targetBlockPos = Point3.Round(hit.point + hit.normal * 0.5f);
            Point3 playerPos = Point3.Round(transform.position);

            WalkList = null;
            new Thread(() => WalkList = Pathfinding.FindPath(playerPos, targetBlockPos, voxelTerrain)).Start();
        }
    }

    void FixedUpdate()
    {
        if (WalkList != null && WalkList.Count > 0)
        {
            Point3 TargetPoint = WalkList[0];

            characterController.Move((TargetPoint - transform.position).normalized * speed * Time.fixedDeltaTime);

            //transform.Translate((TargetPoint - transform.position).normalized * Time.fixedDeltaTime * speed);

            if (Vector3.Distance(transform.position, TargetPoint) < speed * Time.fixedDeltaTime)
            {
                //lastPoint = new Point3(WalkList[0].x, 1, WalkList[0].y);
                WalkList.Remove(TargetPoint);
                //GameObject.CreatePrimitive(PrimitiveType.Cube).transform.position = TargetPoint;
                if (WalkList.Count == 0)
                    transform.position = TargetPoint;
            }
        }
    }

    public void OnTerrainChange()
    {
        if (WalkList != null && WalkList.Count > 0)
        {
            Point3 lastWaypoint = WalkList[WalkList.Count - 1];
            lastWaypoint = new Point3(lastWaypoint.x, voxelTerrain.HeightmapLayer(lastWaypoint.x, lastWaypoint.z), lastWaypoint.z);

            WalkList = Pathfinding.FindPath(Point3.Round(transform.position), lastWaypoint, voxelTerrain);
        }
    }
}
